import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { LogicalSize, LogicalPosition } from '@tauri-apps/api/dpi'
import { currentMonitor } from '@tauri-apps/api/window'
import { Store } from '@tauri-apps/plugin-store';
import { nextTick } from 'vue'
const pluginBase = '/' + __PLUGIN_NAME__;

export const useWindow = () => {
    const createWebviewWindow = async (
        title: string,
        label: string,
        width: number,
        height: number,
        alwaysOnTop = false,
        resizable = false,
        minW = 310,
        minH = 495,
        shadow = false,
        skipTaskbar = false,
        position?: { x: number; y: number }
    ) => {
        const webview = new WebviewWindow(label, {
            title: title,
            url: `${pluginBase}/${label}`,
            fullscreen: false,
            resizable: resizable,
            center: !position, // 如果设置了position，就不居中
            width: width,
            height: height,
            minHeight: minH,
            minWidth: minW,
            skipTaskbar: skipTaskbar,
            shadow,
            decorations: false,
            transparent: true,
            titleBarStyle: 'overlay', // mac覆盖标签栏
            hiddenTitle: true, // mac隐藏标题栏
            visible: true,
            alwaysOnTop
        })

        await webview.once('tauri://created', async () => {

        })

        await webview.once('tauri://error', async (e) => {
            console.log("创建失败了窗口", e)
            // TODO 这里利用错误处理的方式来查询是否是已经创建了窗口,如果一开始就使用WebviewWindow.getByLabel来查询在刷新的时候就会出现问题 (nyh -> 2024-03-06 23:54:17)
            await checkWinExist(label)
        })

        return webview
    }
    /**
    * 检查窗口是否存在
    * @param L 窗口标签
    */
    const checkWinExist = async (L: string) => {
        const isExistsWinds = await WebviewWindow.getByLabel(L)
        if (isExistsWinds) {
            nextTick().then(async () => {
                // 如果窗口已存在，首先检查是否最小化了
                const minimized = await isExistsWinds.isMinimized()
                // 检查是否是隐藏
                const hidden = await isExistsWinds.isVisible()
                if (!hidden) {
                    await isExistsWinds.show()
                }
                if (minimized) {
                    // 如果已最小化，恢复窗口
                    await isExistsWinds.unminimize()
                }
                // 如果窗口已存在，则给它焦点，使其在最前面显示
                await isExistsWinds.setFocus()
            })
        }
    }

    const setWinPosition = async (win: WebviewWindow, position: any) => {
        const monitor = await currentMonitor();
        if (monitor) {
            const size = await win.innerSize();
            if (position == 'top-right') {
                win.setPosition(new LogicalPosition(monitor.position.x + monitor.size.width - 200, 50))
            } else if (position == "bottom-left") {
                win.setPosition(new LogicalPosition(20, monitor.position.y + monitor.size.height - size.height - 20))
            } else if (position == "bottom-right") {
                win.setPosition(new LogicalPosition(monitor.position.x + monitor.size.width - size.width - 20, monitor.position.y + monitor.size.height - size.height - 20))
            } else if (position == "center") {
                win.setPosition(new LogicalPosition((monitor.position.x + monitor.size.width) / 2 - (size.width / 2),
                    (monitor.position.y + monitor.size.height) / 2 - (size.height / 2)))
            } else {
                win.setPosition(new LogicalPosition(position.x, position.y))
            }
        }
    }

    const setWinPositionByLable = async (label: string, position: any) => {
        const win = await WebviewWindow.getByLabel(label)
        if (win) {
            const monitor = await currentMonitor();
            if (monitor) {
                const size = await win.innerSize();
                if (position == 'top-right') {
                    win.setPosition(new LogicalPosition(
                        monitor.position.x + monitor.size.width - size.width - 20, 50
                    ))
                } else if (position == "top-left") {
                    win.setPosition(new LogicalPosition(20, 50))
                } else if (position == "bottom-left") {
                    win.setPosition(new LogicalPosition(20, monitor.position.y + monitor.size.height - size.height - 20))
                } else if (position == "bottom-right") {
                    win.setPosition(new LogicalPosition(monitor.position.x + monitor.size.width - size.width - 20, monitor.position.y + monitor.size.height - size.height - 20))
                } else if (position == "center") {
                    win.setPosition(new LogicalPosition((monitor.position.x + monitor.size.width) / 2 - (size.width / 2),
                        (monitor.position.y + monitor.size.height) / 2 - (size.height / 2)))
                } else {
                    win.setPosition(new LogicalPosition(position.x, position.y))
                }
            }
        }

    }

    const closWebviewWindow = async (label: string) => {
        const isExistsWinds = await WebviewWindow.getByLabel(label)
        if (isExistsWinds) {
            isExistsWinds.close()
        }
    }

    const getWebviewWindow = async (label: string) => {
        return await WebviewWindow.getByLabel(label)
    }

    // 调整窗口大小
    const setWebviewWindowSize = async (label: string, width: number, height: number) => {
        const win = await WebviewWindow.getByLabel(label);
        if (win) {
            const max = await win.isMaximized();
            const min = await win.isMinimized();
            if (!max && !min) {
                win.setSize(new LogicalSize(width, height))
            }
        }
    }

    let cachedWindowPosition: Record<string, any> = {};

    // 调整窗口是否穿透
    const setWebviewWindowPenetrate = async (label: string, isPenetrate: boolean) => {
        const win = await WebviewWindow.getByLabel(label);
        if (win) {
            await win.setIgnoreCursorEvents(isPenetrate);
        }
    }

    // 将窗口坐标转换为屏幕坐标
    const convertToScreen = async (label: string, screenX: number, screenY: number) => {
        if (!cachedWindowPosition[label]) {
            const currentWindow = await WebviewWindow.getByLabel(label);
            if (currentWindow) {
                cachedWindowPosition[label] = await currentWindow.innerPosition();
                saveWindowPosition(cachedWindowPosition[label]);
            }
        }
        return {
            winX: screenX - cachedWindowPosition[label].x,
            winY: screenY - cachedWindowPosition[label].y
        }
    }

    const saveWindowPosition = async (data: any) => {
        const store = await Store.load(__PLUGIN_NAME__ + ".json");
        await store.set("desktopWidgetPosition", JSON.stringify(data));
    }

    const clearCachedWindowPosition = (label: string) => {
        cachedWindowPosition[label] = null;
    }
    return {
        setWebviewWindowSize,
        setWebviewWindowPenetrate,
        getWebviewWindow,
        createWebviewWindow,
        setWinPosition,
        setWinPositionByLable,
        closWebviewWindow,
        convertToScreen,
        clearCachedWindowPosition
    }
}